/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2020-02-02 10:06:15
 * @LastEditors: cxguo
 * @LastEditTime: 2020-06-13 14:10:17
 */

import XEUtils from 'xe-utils'

export default {
  methods: {
    addData() {
      const data = this.currentNode
      if (!data) return this.$message.error('请选择一个分类')
      if (data.id !== '0' && data.isDefault === '1') return this.$message.error('默认分类下，不可新增！')
      const newChild = { id: null, name: '新建分类', edit: true, children: [] }
      newChild.pid = data.id
      this.currentNode = newChild
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
      this.setInputSelect()
    },
    delData() {
      const data = this.currentNode
      if (!data) return this.$message.error('请选择一个分类')
      const { id, name } = data
      if (data.isDefault === '1') return this.$message.error('默认分类不可删除！')
      this.$confirm(`确定要删除分类[${name}]吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = id
        this.delPostData(params)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    updateData() {
      const data = this.currentNode
      if (!data) return this.$message.error('请选择一个分类')
      if (data.isDefault === '1') return this.$message.error('默认分类不可编辑！')
      this.$set(this.currentNode, 'edit', true)
      this.setInputSelect()
    },
    listData(refresh = false) {
      this.loading = true
      return new Promise((resolve) => {
        this.listDataFun().then(res => {
          this.loading = false
          if (res.data.flag) {
            const data = res.data.data
            const cateTreedata = XEUtils.toArrayTree(data, {
              key: 'id',
              parentKey: 'pid'
            })
            resolve(cateTreedata)
            this.cateTreedata = cateTreedata
            this.cateData = data
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // private
    setInputSelect() {
      setTimeout(() => {
        const domInput = document.querySelector('.el-tree-node input')
        if (!domInput) return
        domInput.focus()
        domInput.select()
      }, 200)
    }

  }
}
